<template>
  <div class="menu-management">
    <!-- 搜索区域 -->
    <div class="search-form">
      <el-form :model="searchForm" inline>
        <el-form-item :label="$t('page.system.menu.menuName')">
          <el-input
            v-model="searchForm.menuName"
            :placeholder="$t('page.system.menu.menuName')"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item :label="$t('page.system.menu.status')">
          <el-select
            v-model="searchForm.status"
            :placeholder="$t('page.system.menu.status')"
            clearable
            style="width: 120px"
          >
            <el-option :label="$t('page.system.menu.normal')" value="0" />
            <el-option :label="$t('page.system.menu.disabled')" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('page.system.menu.perms')">
          <el-input
            v-model="searchForm.perms"
            :placeholder="$t('page.system.menu.perms')"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            {{ $t('page.system.menu.search') }}
          </el-button>
          <el-button @click="handleReset">
            {{ $t('page.system.menu.reset') }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 工具栏 -->
    <div class="toolbar">
      <el-button type="primary" @click="handleAdd">
        + {{ $t('page.system.menu.add') }}
      </el-button>
      <el-button @click="handleExpandAll">
        {{ isExpandAll ? $t('page.system.menu.collapseAll') : $t('page.system.menu.expandAll') }}
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="loading"
      :data="tableData"
      row-key="id"
      border
      stripe
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      :default-expand-all="isExpandAll"
    >
      <el-table-column
        prop="menuName"
        :label="$t('page.system.menu.menuName')"
        min-width="200"
        show-overflow-tooltip
      />
      <el-table-column
        prop="path"
        :label="$t('page.system.menu.path')"
        min-width="150"
        show-overflow-tooltip
      />
      <el-table-column
        prop="component"
        :label="$t('page.system.menu.component')"
        min-width="150"
        show-overflow-tooltip
      />
      <el-table-column
        prop="perms"
        :label="$t('page.system.menu.perms')"
        min-width="150"
        show-overflow-tooltip
      />
      <el-table-column
        prop="status"
        :label="$t('page.system.menu.status')"
        width="100"
        align="center"
      >
        <template #default="{ row }">
          <el-tag :type="row.status === '0' ? 'success' : 'danger'">
            {{ row.status === '0' ? $t('page.system.menu.normal') : $t('page.system.menu.disabled') }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="createTime"
        :label="$t('page.system.menu.createTime')"
        width="180"
        align="center"
      />
      <el-table-column
        :label="$t('page.system.menu.operation')"
        width="200"
        align="center"
        fixed="right"
      >
        <template #default="{ row }">
          <el-button
            size="small"
            type="primary"
            text
            @click="handleEdit(row)"
          >
            {{ $t('page.system.menu.edit') }}
          </el-button>
          <el-button
            size="small"
            type="success"
            text
            @click="handleAddChild(row)"
          >
            {{ $t('page.system.menu.add') }}
          </el-button>
          <el-button
            size="small"
            type="danger"
            text
            @click="handleDelete(row)"
          >
            {{ $t('page.system.menu.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 菜单表单弹窗 -->
    <MenuForm
      v-model:visible="formVisible"
      :form-data="currentMenu"
      :is-edit="isEdit"
      @submit="handleFormSubmit"
    />
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import {
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElMessageBox,
  ElOption,
  ElSelect,
  ElTable,
  ElTableColumn,
  ElTag,
} from 'element-plus';

import type { Menu, MenuFormData, MenuListParams } from '#/api/system/menu';
import { deleteMenuApi, getMenuListApi } from '#/api/system/menu';
import { $t } from '#/locales';

import MenuForm from './components/MenuForm.vue';

// 搜索表单
const searchForm = reactive<MenuListParams>({
  menuName: '',
  status: '',
  perms: '',
});

// 表格数据
const tableData = ref<Menu[]>([]);
const loading = ref(false);
const isExpandAll = ref(false);

// 表单弹窗
const formVisible = ref(false);
const currentMenu = ref<Partial<MenuFormData>>({});
const isEdit = ref(false);

// 获取菜单列表
const getMenuList = async () => {
  loading.value = true;
  try {
    const params: MenuListParams = { ...searchForm };
    // 移除空值
    Object.keys(params).forEach(key => {
      if (params[key as keyof MenuListParams] === '') {
        delete params[key as keyof MenuListParams];
      }
    });
    const data = await getMenuListApi(params);
    tableData.value = data;
  } catch (error) {
    console.error('获取菜单列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  getMenuList();
};

// 重置搜索
const handleReset = () => {
  searchForm.menuName = '';
  searchForm.status = '';
  searchForm.perms = '';
  getMenuList();
};

// 展开/折叠全部
const handleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value;
};

// 新增菜单
const handleAdd = () => {
  currentMenu.value = {
    menuName: '',
    path: '',
    component: '',
    status: '0',
    perms: '',
    parentId: 0,
  };
  isEdit.value = false;
  formVisible.value = true;
};

// 新增子菜单
const handleAddChild = (row: Menu) => {
  currentMenu.value = {
    menuName: '',
    path: '',
    component: '',
    status: '0',
    perms: '',
    parentId: row.id,
  };
  isEdit.value = false;
  formVisible.value = true;
};

// 编辑菜单
const handleEdit = (row: Menu) => {
  currentMenu.value = { ...row };
  isEdit.value = true;
  formVisible.value = true;
};

// 删除菜单
const handleDelete = async (row: Menu) => {
  // 检查是否有子菜单
  if (row.children && row.children.length > 0) {
    ElMessage.warning($t('page.system.menu.message.hasChildren'));
    return;
  }

  try {
    await ElMessageBox.confirm(
      $t('page.system.menu.message.deleteConfirm'),
      $t('page.system.menu.delete'),
      {
        type: 'warning',
      }
    );
    await deleteMenuApi(row.id);
    ElMessage.success($t('page.system.menu.message.deleteSuccess'));
    getMenuList();
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除菜单失败:', error);
    }
  }
};

// 表单提交
const handleFormSubmit = () => {
  formVisible.value = false;
  getMenuList();
};

// 初始化
onMounted(() => {
  getMenuList();
});
</script>

<style scoped>
.menu-management {
  padding: 20px;
}

.search-form {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.toolbar {
  margin-bottom: 20px;
}
</style> 
